import axios from 'axios'
import CryptoJS from 'crypto-js'


const requester = axios.create({
	baseURL: import.meta.env.VITE_API_PREFIX,
  timeout: 5000
})


export function getCid() {
  return 'G3nius M0nkeyhbd'
}


export function setTokenFactor(tokenFactor) {
  localStorage.setItem('tokenFactor', tokenFactor)
}


export function resetTokenFactor(tokenFactor) {
  localStorage.setItem('tokenFactor', '0')
}


function binHash(str1, str2) {
  try {
    var md5 = CryptoJS.algo.MD5.create()
    md5.update(str1)
    md5.update(str2)
    return md5.finalize().toString()
  }
  catch {
    return ''
  }
}


function requestFormula(body) {
  return {
    token: binHash(localStorage.getItem('tokenFactor'), getCid()),
    version: 'v0.0.0',
    body: body
  }
}


export function post(path, req=null) {
  var formula = requestFormula(req)
  return new Promise(function(resolve, reject) {
    requester.post(path, formula).then(function(res) {
      var responseFormula = res.data
      // OK response.
      if (responseFormula.code == 'OK') {
        resolve(responseFormula.body)
      }
      else if (responseFormula.code == 'BAD_TOKEN') {
        window.location.href = '/#/login'
        reject(responseFormula)
      }
      // Other response.
      else {
        ElNotification({
          title: `未捕获错误 ${responseFormula.code}`,
          message: `${responseFormula.message}`,
          type: 'error',
          position: 'bottom-right',
        })
        reject(responseFormula)
      }
    })
  })
}
